import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-09-05
 * Time:21:45
 */

/**
 * ["cat","bt","hat","tree"]
 * "atach"
 */

/**
 * 力扣1160:拼写单词
 */

public class countCharacters {
    public static void main(String[] args) {
        String[] words = {"cat","bt","hat","tree"};
        String chars = "atach";
        System.out.println(countCharacters(words, chars));
    }
    public static int countCharacters(String[] words, String chars) {
        Map<Character,Integer> charsWord = new HashMap<>();
        int len = chars.length();
        for (int i = 0; i < len; i++) {
            char ch = chars.charAt(i);
            //getOrDefault 获取ch的val,这里是0是如果加的话会覆盖所以一样
            charsWord.put(ch,charsWord.getOrDefault(ch,0)+1);
        }
        int num = 0;
        //words中一个单词一个单词的来
        for (String word:words) {
            Map<Character,Integer> wordsWord = new HashMap<>();
            int wordlen = word.length();
            for (int i = 0; i < wordlen; i++) {
                char ch = word.charAt(i);
                wordsWord.put(ch,wordsWord.getOrDefault(ch,0)+1);
            }
            boolean isTrue = true;
            for (int i = 0; i < wordlen; ++i) {
                char c = word.charAt(i);
                if (charsWord.getOrDefault(c, 0) < wordsWord.getOrDefault(c, 0)) {
                    isTrue = false;
                    break;
                }
            }
            if (isTrue) {
                num += word.length();
            }
        }
        return num;
    }
}
